<script setup lang="tsx">
import type { Component } from 'vue';
import { defineComponent, h, nextTick, reactive, ref, watch } from 'vue';
import { NButton, NGradientText, NIcon, NInput, NInputNumber, NPopconfirm, NTag, useMessage } from 'naive-ui';
import type {
  CascaderOption,
  DataTableColumns,
  DataTableRowKey,
  DrawerPlacement,
  // FormInst,
  MenuOption
  // NumberAnimationInst
} from 'naive-ui';
import {
  Beer,
  BookmarkOutline,
  CaretDownOutline,
  DiamondOutline,
  FishOutline as FishIcon,
  FlashOutline,
  LogoStackoverflow,
  MagnetOutline,
  PawOutline as PawIcon,
  Woman
} from '@vicons/ionicons5';
import {
  fetchAddDetail,
  fetchBatchAddDetail,
  fetchDeleteBatchDetail,
  fetchDeleteDetail,
  fetchDeleteOrder,
  fetchEditDetail,
  // fetchEditOrder,
  getDishSearch,
  fetchGetAllDish,
  fetchGetDetailByID
} from '@/service/api';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';

defineOptions({
  name: 'Detail'
});

interface Props {
  ordertitle: string;
  currentid: any;
  order: Api.Food.Order | undefined;
  currentSale: GLfloat;
}

const props_current = defineProps<Props>();

interface Emits {
  (e: 'closedd'): void;
  (e: 'onDeleted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const loading = defineModel<boolean>('loading', {
  default: false
});

function closeDrawer() {
  visible.value = false;
}

type Model = Pick<Api.Food.Detail, 'dish' | 'orders' | 'number' | 'price' | 'message'>;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    dish: '',
    orders: '',
    number: 1,
    price: 0,
    message: ''
  };
}

function renderIcon(icon: Component) {
  return () => h(NIcon, null, { default: () => h(icon) });
}

const appStore = useAppStore();
// const disabled = ref(true);
const message = useMessage();
// 集联数据
// const checkStrategyIsChild = ref(true);
// const cascade = ref(true);
// const showPath = ref(true);
// const hoverTrigger = ref(true);
// const filterable = ref(true);
// const responsiveMaxTagCount = ref(true);
// const clearFilterAfterSelect = ref(true);
const multiDetail = ref<string[]>();
const memLabel = ref({});
// const dishlist = ref<Api.Food.DishList>();
// const dishOptions = ref<CommonType.Option<string>[]>([]);
// const dishOptions2 = ref<MenuOption[]>([]);
const menuOptionList = ref<MenuOption[]>([]);
const currentdata = ref<Api.Food.DetailList>();
const totalPrice = ref(0); // 总价
const afterPrice = ref<GLfloat>(0.0); // 折后价
const retry = ref(0);
const 酒水Item = ref([]);
const 酒水不打折 = ref(0);
const checkedRowKeys = ref<string[]>([]);
const checkedRowKeysRefDetail = ref<DataTableRowKey[]>([]);
const placement = ref<DrawerPlacement>('bottom');
// const numberAnimationInstRef = ref<NumberAnimationInst | null>(null);
// const formRef = ref<FormInst | null>(null);
// const currentSelectOrderNew = ref<Api.Food.Order | null>(null);
const currentMenuSelect = ref('');
const currentMenuSelectOption = ref<MenuOption[]>([]);
const searchValue = ref('');
// const rowKey = (row: Api.Food.Detail) => row.id;
const handleCheck = (rowKeys: DataTableRowKey[]) => {
  checkedRowKeysRefDetail.value = rowKeys;
};

function closedd() {
  emit('closedd');
}

async function handleChange(v: string) {
  message.success(`搜索菜单: ${v}`);
  searchValue.value = v;
  const datas = await getDishSearch(v);
  menuOptionList.value = [];
  const tmp = new Map();
  datas.data.records?.forEach(item => {
    if (tmp.has(item.text)) {
      if (item.children.length > 0) {
        item.children.forEach(item2 => {
          const tt = tmp.get(item2.category);
          tt.push({
            label: `${item2.name} ${item2.price}`,
            value: item2.id,
            disabled: item2.disabled,
            message: item2.message
          });
          tmp.set(item2.category, tt);
        });
      }
    } else {
      const tmp_list = [];
      item.children.forEach(item2 => {
        console.log('item2', item2);
        tmp_list.push({
          label: `${item2.dish.name} ${item2.dish.price}`,
          name: item2.dish.name,
          value: item2.id,
          disabled: item2.disabled,
          message: item2.message
        });
      });
      tmp.set(item.text, tmp_list);
    }
  });

  menu.forEach(m => {
    tmp.forEach((value, key) => {
      if (key === m) {
        const menuTmp = {
          label: key,
          key,
          value: key,
          nochildren: value,
          message: value
        };

        menuOptionList.value.push(menuTmp);
      }
    });
  });

  if (currentMenuSelect.value !== '') {
    menuOptionList.value.forEach(item => {
      if (item.label === currentMenuSelect.value) {
        currentMenuSelectOption.value = item.children;
      }
    });
  }
}

function clearsearch() {
  message.info(`Clear Search`);
}

async function getDish() {
  model.orders = props_current.currentid;
  const datas = await fetchGetAllDish();

  if (datas.error) {
    message.error(datas.error.message);
  } else {
    retry.value += 1;

    if (retry.value === 1) {
      // dishOptions2.value = [];
      // menuOptionList.value = [];
      menuOptionList.value = [];
      // console.log('11111', menuOptionList.value);
      // console.log('获取菜单 retry', retry.value);
      // dishlist.value = datas.data;
      // console.log('dishlist', dishlist.value);

      const tmp = new Map();
      datas.data.records?.forEach(item => {
        // console.log('2222', item.name, searchValue.value, item.name.indexOf(searchValue.value));
        if (tmp.has(item.category)) {
          const tt = tmp.get(item.category);
          memLabel.value[item.id] = { name: item.name, kind: item.category, price: item.price };
          tt.push({
            label: `${item.name} ${item.price}`,
            value: item.id,
            name: item.name,
            disabled: item.disabled
          });
          tmp.set(item.category, tt);
        } else {
          memLabel.value[item.id] = { name: item.name, kind: item.category, price: item.price };
          tmp.set(item.category, [
            {
              label: `${item.name} ${item.price}`,
              value: item.id,
              name: item.name,
              disabled: item.disabled
            }
          ]);
        }
      });
      // console.log('ttttt', tmp);
      tmp.forEach((value, key) => {
        const menuTmp = {
          label: key,
          key,
          value: key,
          nochildren: value
        };

        // console.log('kkkk', key);

        menuOptionList.value.push(menuTmp);
        // dishOptions2.value.push({
        //   // type: 'group',
        //   label: key,
        //   value: key,
        //   children: value
        // });
      });

      if (currentMenuSelect.value !== '') {
        menuOptionList.value.forEach(item => {
          if (item.label === currentMenuSelect.value) {
            currentMenuSelectOption.value = item.children;
          }
        });
      }
      console.log('dishOptions', menuOptionList.value);
    } else if (retry.value > 5) {
      console.log('使用缓存菜单 retry', retry.value);
      retry.value = 0;
      getDish();
    }
  }
  // getDishOptions();
}

function handleUpdateValue(value: string[], options: CascaderOption[]) {
  console.log(value, options);
  multiDetail.value = value;
  // model.dish = value;
}

function resets() {
  // model = {
  //   dish: '',
  //   orders: props_current.currentid,
  //   number: 1,
  //   price: 0,
  //   message: ''
  // };
  model.dish = '';
  multiDetail.value = [];
}

async function handleValidateClick() {
  console.log('ddd', model);

  // formData.value = {
  //   dish: String(formValue.value.dish),
  //   orders: String(formValue.value.orders),
  //   number: formValue.value.number,
  //   message: formValue.value.message
  // };

  const tmp = {
    dish: multiDetail.value?.join(),
    orders: String(props_current.currentid),
    number: model.number,
    message: model.message
  };
  const datas = await fetchBatchAddDetail(tmp);
  if (datas.error) {
    message.error('添加菜单失败');
  } else {
    message.success('添加菜单成功');
    refreshDetail();
    resets();
  }
}

// async function getDataDetail() {
//   console.log('3');
//   const datas = await fetchGetDetailByID(props_current.currentid);
//   if (datas.error) {
//     message.error(`code: ${datas.error.response?.status} 错误信息：${datas.error.response?.data.msg}`);
//   }

//   if (datas.data !== null) {
//     currentdata.value = datas.data;
//     console.log('datas.log', datas.data);
//   }
// }

async function handleBatchDeleteDetail() {
  console.log(checkedRowKeysRefDetail.value);
  const ids: string[] = [];
  checkedRowKeysRefDetail.value.forEach(id => {
    ids.push(id.toString());
  });

  const datas = await fetchDeleteBatchDetail(ids);
  if (!datas.error) {
    window.$message?.success($t('common.deleteSuccess'));
    console.log(datas.error);
  } else {
    window.$message?.error(datas.error.message);
  }
  //   console.log(checkedRowKeys.value);

  refreshDetail();
}

async function handleDeleteDetail(id: string) {
  const datas = await fetchDeleteDetail(id);
  if (datas.error) {
    message.error(`删除订单菜品失败 ${datas.error.response?.data.msg}`);
  }

  refreshDetail();
}

async function refreshDetail() {
  const datas = await fetchGetDetailByID(props_current.currentid);
  if (datas.error) {
    if (datas.error.response?.status === 404) {
      message.warning(`桌号 ${props_current.currentid} 还未点菜`);
    } else {
      message.error(`code: ${datas.error.response?.status} 错误信息：${datas.error.response?.data.msg}`);
    }
  }
  // console.log('detail id ', props_current.currentid, datas);
  totalPrice.value = 0;
  afterPrice.value = 0;
  酒水不打折.value = 0;
  // console.log('酒水不打折', 酒水Item.value);
  if (datas.data.records !== null) {
    currentdata.value = datas.data;
    // console.log('ccccccc', currentdata);
    // const lllength = currentdata.value?.records.length;
    currentdata.value.records.forEach((item, index) => {
      let status = false;
      // currentdata.value.records[index].id2 = lllength - index;
      // console.log('123333', 酒水Item.value);
      酒水Item.value.forEach(item2 => {
        // console.log('11111', item.dish, item2.value, item.dish === String(item2.value));
        if (item.dish === String(item2.value)) {
          // console.log('2222', item, item2);
          status = true;
        }
      });
      if (status) {
        酒水不打折.value += item.price;
      } else {
        totalPrice.value += item.price;
      }
    });
    afterPrice.value = totalPrice.value * props_current.currentSale;
  } else {
    // console.log('3333 delete currentdata');
    currentdata.value = null;
  }
  loading.value = true;
  nextTick().then(() => {
    loading.value = false;
  });
  console.log('currentdata', currentdata.value, afterPrice.value, totalPrice.value, 酒水不打折.value);
}

const page = ref(1);

const handlePageChange = curPage => {
  page.value = curPage;
};

const getDataIndex = key => {
  return currentdata.value.records.findIndex(item => item.id === key);
};

const ShowOrEdit = defineComponent({
  props: {
    value: [String, Number],
    onUpdateValue: [Function, Array]
  },
  setup(props) {
    const isEdit = ref(false);
    const inputRef = ref(null);
    const inputValue = ref(props.value);
    function handleOnClick() {
      isEdit.value = true;
      nextTick().then(() => {
        inputRef.value.focus();
      });
    }
    function handleChange() {
      props.onUpdateValue(inputValue.value);
      isEdit.value = false;
    }
    function handleBlur() {
      isEdit.value = false;
    }
    return () =>
      h(
        'div',
        {
          style: 'min-height: 22px',
          onClick: handleOnClick
        },
        isEdit.value
          ? h(NInput, {
              ref: inputRef,
              value: inputValue.value,
              onUpdateValue: v => {
                inputValue.value = v;
              },
              buttonPlacement: 'both',
              onChange: handleChange,
              onBlur: handleBlur
            })
          : props.value
      );
  }
});

async function handleDeleteOrder() {
  const { error, data } = await fetchDeleteOrder(props_current.currentid);
  if (!error) {
    window.$message?.success($t('common.deleteSuccess'));
    console.log(data);
  } else {
    window.$message?.error(error.message);
  }
  //   onDeleted();
  emit('onDeleted');
}

// async function handleSubmit() {
//   // 准备数据
//   console.log('handleSubmit', props_current.order);
//   currentSelectOrderNew.value = props_current.order;
//   currentSelectOrderNew.value.price = totalPrice.value + 酒水不打折.value;
//   currentSelectOrderNew.value.afterprice = afterPrice.value + 酒水不打折.value;
//   currentSelectOrderNew.value.current = '已结账';
//   currentSelectOrderNew.value.id = props_current.currentid;

//   const datas = await fetchEditOrder(props_current.currentid, currentSelectOrderNew.value);
//   if (datas.error) {
//     message.error(datas.error.message);
//   } else {
//     // dishactive.value = false;
//     emit('closedd');
//     message.success(`结账成功 ${datas.data}`);
//   }
//   closeDrawer();
//   message.success(`结账成功`);
// }

function handlePositiveClick() {
  handleDeleteOrder();
  //   dishactive.value = false;
  emit('closedd');
  message.info('已删除订单');
  refreshDetail();
}

function handleNegativeClick() {
  message.info('已取消');
}

const columesDish: DataTableColumns<Api.Food.Detail> = [
  {
    key: 'dish',
    title(column) {
      return h(
        NGradientText,
        {
          size: '20',
          type: 'info'
        },
        { default: () => '菜品' }
      );
    },
    align: 'left',
    width: 100,
    render: row => {
      const tmp = memLabel.value[row.dish];
      if (tmp !== undefined) {
        // console.log('memLabel', tmp, tmp.name);
        return tmp.name;
      }
      return row.dish;
    }
  },
  {
    key: 'price',
    title(column) {
      return h(
        NGradientText,
        {
          size: '20',
          type: 'warning'
        },
        { default: () => '总价' }
      );
    },
    align: 'center'
  },
  {
    key: 'single',
    title(column) {
      return h(
        NGradientText,
        {
          size: '20',
          type: 'warning'
        },
        { default: () => '单价' }
      );
    },
    align: 'center',
    render: row => {
      const tmp = memLabel.value[row.dish];
      if (tmp !== undefined) {
        // console.log('memLabel', tmp, tmp.name);
        return tmp.price;
      }
      return '未找到';
    }
  },
  {
    key: 'number',
    title(column) {
      return h(
        NGradientText,
        {
          size: '20',
          type: 'error'
        },
        { default: () => '数量' }
      );
    },
    width: 100,
    align: 'center',
    render(row) {
      const index = getDataIndex(row.id);
      if (props_current.order.current === '已结账') {
        return row.number;
      }
      return h(ShowOrEdit, {
        value: String(row.number),
        async onUpdateValue(v) {
          currentdata.value.records[index].number = Number(v);
          // 发起修改
          const datas = await fetchEditDetail(row.id, currentdata.value.records[index]);
          if (datas.error) {
            message.error(`修改订单菜品失败 ${datas.error.message}`);
          }
          refreshDetail();
        }
      });
    }
  },
  {
    key: 'operate',
    title(column) {
      return h(
        NGradientText,
        {
          size: '20',
          type: 'success'
        },
        { default: () => $t('common.operate') }
      );
    },
    align: 'center',
    render: row => (
      <div class="flex-center gap-8px">
        {/* <NButton type="warning" ghost size="small" onClick={() => actived('bottom', row.id)}>
            {$t('common.order')}
          </NButton> */}
        {/* <NButton type="primary" ghost size="small" onClick={() => edit(row.id)}>
          {$t('common.edit')}
        </NButton> */}
        <NPopconfirm onPositiveClick={() => handleDeleteDetail(row.id)}>
          {{
            default: () => $t('common.confirmDelete'),
            trigger: () => (
              <NButton type="error" ghost size="small">
                {$t('common.delete')}
              </NButton>
            )
          }}
        </NPopconfirm>
      </div>
    )
  }
];

const menu = ['特色烤串', '把把系列', '烤串系列', '酒水饮料', '特色菜系列', '江湖菜系列'];

const rules = {
  dish: {
    required: true,
    message: '请选择菜品',
    trigger: 'blur'
  },
  order: {
    required: true,
    message: '请输入订单号',
    trigger: 'blur'
  }
};

function finshed() {
  message.success('上传成功');
  refreshDetail();
}

watch(visible, () => {
  if (visible.value) {
    getDish();
    // getDataDetail();
    refreshDetail();
  }
});
const collapsed = ref(false);

function renderMenuLabel(option: MenuOption) {
  if ('href' in option) {
    return h('a', { href: option.href, target: '_blank' }, option.label as string);
  }
  return option.label as string;
}

function renderMenuIcon(option: MenuOption) {
  // 渲染图标占位符以保持缩进
  if (option.key === 'sheep-man') return true;
  // 返回 falsy 值，不再渲染图标及占位符
  if (option.key === 'food') return null;

  if (option.key === '特色烤串') {
    return h(NIcon, null, { default: () => h(MagnetOutline) });
  }

  if (option.key === '酒水饮料') {
    return h(NIcon, null, { default: () => h(Beer) });
  }

  if (option.key === '把把系列') {
    return h(NIcon, null, { default: () => h(LogoStackoverflow) });
  }

  if (option.key === '烤串系列') {
    return h(NIcon, null, { default: () => h(DiamondOutline) });
  }

  if (option.key === '江湖菜系列') {
    return h(NIcon, null, { default: () => h(FishIcon) });
  }

  if (option.key === '特色菜系列') {
    return h(NIcon, null, { default: () => h(PawIcon) });
  }

  if (option.key === '基础消费') {
    return h(NIcon, null, { default: () => h(Woman) });
  }
  return h(NIcon, null, { default: () => h(BookmarkOutline) });
}

function expandIcon() {
  return h(NIcon, null, { default: () => h(CaretDownOutline) });
}

function handleMenuUpdateValue(key: string, item: MenuOption) {
  currentMenuSelect.value = key;
  // message.info(`[onUpdate:value]: ${JSON.stringify(key)}`);
  // message.info(`[onUpdate:value]: ${JSON.stringify(item)}`);
  menuOptionList.value.forEach(item => {
    if (item.label === key) {
      currentMenuSelectOption.value = item.nochildren;
    }
  });
}
const showSuffix = ref(false);

async function handleValidateClickSingle(id: string) {
  console.log('ddd', id);

  // formData.value = {
  //   dish: String(formValue.value.dish),
  //   orders: String(formValue.value.orders),
  //   number: formValue.value.number,
  //   message: formValue.value.message
  // };

  const tmp = {
    dish: id.toString(),
    orders: String(props_current.currentid),
    number: 1,
    message: model.message
  };
  const datas = await fetchAddDetail(tmp);
  if (datas.error) {
    message.error('添加菜单失败');
  } else {
    message.success('添加菜单成功');
    refreshDetail();
    resets();
  }
}
</script>

<template>
  <!-- 订单菜品详情  -->
  <NDrawer v-model:show="visible" height="95%" resizable :placement="placement" @after-leave="closedd">
    <NDrawerContent :title="props_current.ordertitle" closable>
      <NLayout has-sider position="absolute">
        <NLayoutSider bordered position="absolute" :collapsed-width="480" :width="480" content-style="padding: 2px;">
          <NDataTable
            v-model:checked-row-keys="checkedRowKeys"
            striped
            :columns="columesDish"
            :data="currentdata?.records"
            size="large"
            :flex-height="!appStore.isMobile"
            :loading="loading"
            remote
            :row-key="row => row.id"
            class="sm:h-full"
            :on-update:page="handlePageChange"
            @update:checked-row-keys="handleCheck"
          />
        </NLayoutSider>
        <NLayout position="absolute" content-style="padding: 2px;padding-left: 480px;">
          <NLayoutHeader bordered>
            <NInput
              v-model:value="searchValue"
              placeholder="搜索"
              :clearable="true"
              @update:value="handleChange"
              @clear="clearsearch"
            >
              <template #prefix>
                <NIcon :component="FlashOutline" />
              </template>
            </NInput>
          </NLayoutHeader>
          <NLayoutContent content-style="padding: 2px;">
            <NLayout has-sider>
              <NLayoutSider
                bordered
                collapse-mode="width"
                :collapsed-width="64"
                :width="240"
                :collapsed="collapsed"
                show-trigger
                @collapse="collapsed = true"
                @expand="collapsed = false"
              >
                <NPopover placement="top" trigger="hover">
                  <template #trigger>
                    <NMenu
                      :collapsed="collapsed"
                      :collapsed-width="64"
                      :collapsed-icon-size="22"
                      :options="menuOptionList"
                      :render-label="renderMenuLabel"
                      :render-icon="renderMenuIcon"
                      :expand-icon="expandIcon"
                      @update:value="handleMenuUpdateValue"
                    />
                  </template>
                  <span>点击菜单任意位置点餐</span>
                </NPopover>
              </NLayoutSider>
              <NLayout>
                <!-- <span>内容</span> -->
                <NGrid cols="2 s:2 m:3 l:3 xl:5 2xl:6" responsive="screen">
                  <NGridItem
                    v-for="(item, i) in currentMenuSelectOption"
                    :key="item.label"
                    :class="i % 2 ? 'green' : 'light-green'"
                  >
                    <NCard content-style="width: 350px; height: 300px;" @click="handleValidateClickSingle(item.value)">
                      <NPopover placement="left" trigger="hover">
                        <template #trigger>
                          <NSpace>
                            <NAvatar :size="88" :src="'/img/' + item.name + '.jpg'"></NAvatar>
                            <NFlex vertical>
                              {{ item.label }}
                              <NFlex>
                                <NAvatar
                                  round
                                  :style="{
                                    color: 'red',
                                    backgroundColor: 'white',
                                    fontSize: '50px'
                                  }"
                                  size="medium"
                                >
                                  {{ item.label.split('')[0] }}
                                </NAvatar>
                                <NAvatar
                                  round
                                  :style="{
                                    color: 'red',
                                    backgroundColor: 'white',
                                    fontSize: '50px'
                                  }"
                                  size="medium"
                                >
                                  {{ item.label.split('')[1] }}
                                </NAvatar>
                              </NFlex>
                            </NFlex>
                          </NSpace>
                        </template>
                        <span>{{ item.label }}</span>
                      </NPopover>
                    </NCard>
                  </NGridItem>
                  <NGi v-if="showSuffix" suffix class="suffix" #="{ overflow }">
                    {{ overflow ? '存在溢出' : '不存在溢出' }}
                  </NGi>
                </NGrid>
              </NLayout>
            </NLayout>
          </NLayoutContent>
          <!-- <NLayoutFooter bordered>成府路</NLayoutFooter> -->
        </NLayout>
      </NLayout>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped>
.suffix {
  height: 108px;
  border: 1px solid rgba(0, 128, 0, 0.36);
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
}
.light-green {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
}
.green {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
